package com.tomdd.log.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zx
 * @date 2024年11月26日 15:45
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {
    private static final int CORE_THREAD_SIZE = Runtime.getRuntime().availableProcessors() + 1;

    private static final int MAX_THREAD_SIZE = Runtime.getRuntime().availableProcessors() * 2 + 1;

    private static final int WORK_QUEUE = 1000;

    private static final int KEEP_ALIVE_SECONDS = 60;

    /**
     * 声明一个线程池
     *
     * @return 执行器
     */
    @Bean("CustomerExecutor")
    public Executor asyncExecutor() {
        MyThreadPoolTaskExecutor executor = new MyThreadPoolTaskExecutor();
        //线程池创建时候初始化的线程数
        executor.setCorePoolSize(CORE_THREAD_SIZE);
        //最大线程数5：线程池最大的线程数，只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(MAX_THREAD_SIZE);
        //缓冲队列500：用来缓冲执行任务的队列
        executor.setQueueCapacity(WORK_QUEUE);
        //允许线程的空闲时间60秒：当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        //线程池名的前缀：设置好了之后可以方便我们定位处理任务所在的线程池嘻嘻嘻
        executor.setThreadNamePrefix("customer-thread-pool");
        // 新增线程装饰器
        executor.setTaskDecorator(new BusinessContextDecorator());
        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }
}